package com.example.rabbitmq.ack.direct;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
@Slf4j
public class DirectSendService implements RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String context) {
        // 消息到达交换机这一步
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info(" \n 消息发送成功");
            } else {
                log.info(" \n 消息没有到达交换机----消息发送失败 ==== cause:{} \n" +
                        " ack:{} \n " +
                        " correlationData:{} \n ", cause, correlationData.toString());
            }
        });
        // 消息到达队列这一步
        this.rabbitTemplate.setReturnCallback(this);
        ArrayList<User> users = Lists.newArrayList(
                new User("1", "name1", "gender1"),
                new User("2", "name2", "gender2"),
                new User("3", "name3", "gender3"),
                new User("4", "name4", "gender4"),
                new User("5", "name5", "gender5"),
                new User("6", "name6", "gender6"),
                new User("7", "name7", "gender7"),
                new User("8", "name8", "gender8"),
                new User("9", "name9", "gender9")
        );
        context = JSONObject.toJSONString(users);
        rabbitTemplate.convertAndSend("ackDirectExchange", "ackDirectRouting", context);
    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        log.info(" \n 消息没有到达队列----sender return： success:message:{} \n " +
                " i:{} \n " +
                "s1:{} \n " +
                "s2:{} \n", message.toString(), i, s1, s2);
    }
}
